# -*- coding: utf-8 -*-
# @FileName : Helper.py
# @Time     : 2023/6/8 19:18
# @Author   : Zhong Runke

from flask import render_template, g
import datetime
import uuid
import requests
import os
from email.utils import parsedate_to_datetime

'''统一模板渲染方法'''
def ops_render(template, context={}):
    if 'current_user' in g:
        context['current_user'] = g.current_user
    return render_template(template, **context)






'''获取当前时间'''
def getCurrentDate(format="%Y-%m-%d %H:%M:%S"):
    return datetime.datetime.now().strftime(format)

'''随机生成一个文件名'''
def getFileSalt():
    return str(uuid.uuid1())

def getTimeStamp():
    return datetime.datetime.now()

def saveImageForUrl(url, path=None):
    if path is None:
        pass
    try:
        response = requests.get(url)
        img = response.content
        os.path.join(path, url)
    except:
        return False

def getDictFilterField( db_model,select_filed,key_field,id_list ):
    ret = {}
    query = db_model.query
    if id_list and len( id_list ) > 0:
        query = query.filter( select_filed.in_( id_list ) )

    list = query.all()
    if not list:
        return ret
    for item in list:
        if not hasattr( item,key_field ):
            break

        ret[ getattr( item,key_field ) ] = item
    return ret

def selectFilterObj( obj,field ):
    ret = []
    for item in obj:
        if not hasattr(item, field ):
            break
        if getattr( item,field )  in ret:
            continue
        ret.append( getattr( item,field ) )
    return ret

def getDictListFilterField( db_model,select_filed,key_field,id_list ):
    ret = {}
    query = db_model.query
    if id_list and len( id_list ) > 0:
        query = query.filter( select_filed.in_( id_list ) )

    list = query.all()
    if not list:
        return ret
    for item in list:
        if not hasattr( item,key_field ):
            break
        if getattr( item,key_field ) not in ret:
            ret[getattr(item, key_field)] = []

        ret[ getattr( item,key_field ) ].append(item )
    return ret
